package main

import (
    "gitee.com/zwx784533/zwx2018/app"
    "gitee.com/zwx784533/zwx2018/router"
    "net/http"
    "os"
    "fmt"
    "gitee.com/zwx784533/zwx2018/config"
    "gitee.com/zwx784533/zwx2018/chatroom"
    "github.com/fvbock/endless"
    "syscall"
)

func main()  {
    r := app.New()
    router.Routes(r)
    addr := fmt.Sprintf("%s:%d", config.ServerConf.Ip, config.ServerConf.Port)
    chatroom.Run(r) // 启动聊天室
    err := Run(addr, r)
    fmt.Println(err)

}

// 启动服务
// 平滑重启 kill -SIGHUP $pid
func Run(addr string, handler http.Handler) error  {
    endless.DefaultHammerTime = -1 //
    server := endless.NewServer(addr, handler)
    server.BeforeBegin = func(add string) {
        pid := syscall.Getpid()
        msg := fmt.Sprintf("start at %s, pid=%d", add, pid)
        app.Info(msg)
        fmt.Println(msg)
        savePid(pid)
    }
    err := server.ListenAndServe()
    return err
}

func savePid(pid int)  {
    pidFile, err := os.OpenFile(config.ServerConf.PidFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0755)
    if err != nil {
        panic(err)
        os.Exit(-1)
    }
    pidFile.WriteString(fmt.Sprintf("%d", pid))
    pidFile.Close()
}